﻿Imports System.Net
Imports System.Text
Imports System.IO

Public Class HttpBrowserMobile
    Inherits HttpBrowserBase

    Private cookieManager As New CookieManagerClass

    Public Class CookieManagerClass
        Private m_cookieValues As Dictionary(Of String, String)

        Public ReadOnly Property CookieValues() As Dictionary(Of String, String)
            Get
                If Me.m_cookieValues Is Nothing Then
                    Me.m_cookieValues = New Dictionary(Of String, String)
                End If

                Return Me.m_cookieValues
            End Get
        End Property

        Public Sub PublishCookies(ByVal webRequest As HttpWebRequest)
            Dim sb As New StringBuilder()
            sb.Append("Cookie: ")
            For Each key As String In Me.CookieValues.Keys
                sb.Append(key)
                sb.Append("=")
                sb.Append(Me.CookieValues(key))
                sb.Append("; ")
                sb.Append("$Path=""/""; ")
            Next

            webRequest.Headers.Add(sb.ToString())
            sb = Nothing
            webRequest = Nothing
        End Sub

        Public Sub StoreCookies(ByVal webResponse As HttpWebResponse)
            For x As Integer = 0 To webResponse.Headers.Count - 1
                If webResponse.Headers.Keys(x).ToLower().Equals("set-cookie") Then
                    Me.AddRawCookie(webResponse.Headers(x))
                End If
            Next

            webResponse = Nothing
        End Sub

        Private Sub AddRawCookie(ByVal rawCookieData As String)
            Dim key As String = Nothing
            Dim value As String = Nothing

            Dim entries As String() = Nothing

            If rawCookieData.IndexOf(",") > 0 Then
                entries = rawCookieData.Split(","c)
            Else
                entries = New String() {rawCookieData}
            End If

            For Each entry As String In entries
                Dim cookieData As String = entry.Trim()

                If cookieData.IndexOf(";"c) > 0 Then
                    Dim temp As String() = cookieData.Split(";"c)
                    cookieData = temp(0)
                End If

                Dim index As Integer = cookieData.IndexOf("="c)
                If index > 0 Then
                    key = cookieData.Substring(0, index)
                    value = cookieData.Substring(index + 1)
                End If

                If key IsNot Nothing AndAlso value IsNot Nothing Then
                    Me.CookieValues(key) = value
                End If

                cookieData = Nothing
            Next

            rawCookieData = Nothing
            entries = Nothing
            key = Nothing
            value = Nothing
        End Sub

        Public Overloads Overrides Function ToString() As String
            Dim sb As New StringBuilder()
            sb.Append("[")
            For Each key As String In Me.CookieValues.Keys
                sb.Append("{")
                sb.Append(key)
                sb.Append(",")
                sb.Append(Me.CookieValues(key))
                sb.Append("}, ")
            Next
            If Me.CookieValues.Keys.Count > 0 Then
                sb.Remove(sb.Length - 2, 2)
            End If
            sb.Append("]")

            Return sb.ToString()
        End Function
    End Class

    Public Overrides Function SendRequest(ByVal URL As String, ByVal Method As MethodEnum, ByVal DumpID As String) As String
        Return (SendRequest(URL, Method, String.Empty, DumpID))
    End Function

    Public Overrides Function SendRequest(ByVal URL As String, ByVal Method As MethodEnum, ByVal Content As String, ByVal DumpID As String) As String

        Dim request = DirectCast(WebRequest.Create(URL), HttpWebRequest)

        'request.ServicePoint.Expect100Continue = False
        request.AllowAutoRedirect = True
        request.PreAuthenticate = True
        request.SendChunked = False

        cookieManager.PublishCookies(request)

        Select Case Method
            Case MethodEnum.GetMethod
                request.Method = "GET"
            Case MethodEnum.PostMethod
                request.Method = "POST"
            Case Else
                Throw New Exception("Invalid method specified.")
        End Select

        If Content <> String.Empty Then

            request.ContentType = "application/x-www-form-urlencoded"
            Dim postdata = Encoding.ASCII.GetBytes(Content)
            request.ContentLength = postdata.Length
            Dim st = request.GetRequestStream

            st.Write(postdata, 0, postdata.Length)
            st.Close()

        End If

        Dim response = DirectCast(request.GetResponse, HttpWebResponse)
        Dim sr = New StreamReader(response.GetResponseStream)
        Dim responseBody = sr.ReadToEnd
        sr.Close()

        Dim DumpStamp As String = Format(Now.Year, "0000") & Format(Now.Month, "00") & Format(Now.Day, "00") & Format(Now.Hour, "00") & Format(Now.Minute, "00") & Format(Now.Second, "00") & "_" & DumpID

        If Debug Then DumpCookies(DumpStamp & "_cookies_pre")
        If Debug Then DumpResponse(DumpStamp & "_response", responseBody)

        cookieManager.StoreCookies(response)

        If Debug Then DumpCookies(DumpStamp & "_cookies_post")

        'chiamo le delegate
        If Not PostRequestActions Is Nothing Then
            PostRequestActions.Invoke(responseBody)
        End If

        'restituisco
        Return responseBody

    End Function

    Public Overrides Sub DumpResponse(ByVal ID As String, ByVal Content As String)

        Dim sr As New StreamWriter(DebugFolder & "\" & ID & ".html")
        sr.Write(Content)
        sr.Close()

    End Sub

    Private Sub DumpCookies(ByVal ID As String)

        Dim sr As New StreamWriter(DebugFolder & "\" & ID & ".txt")

        For Each cookie In cookieManager.CookieValues
            sr.Write(cookie.Key)
            sr.Write(Chr(9))
            sr.WriteLine(cookie.Value)
        Next

        sr.Close()

    End Sub

End Class
